/* eslint-disable max-len */
/* eslint-disable no-multiple-empty-lines */
/* eslint-disable prettier/prettier */

import { connect } from 'react-redux';
import React, { Component } from 'react';
import { View, StyleSheet, Text, TouchableOpacity, Alert, Image, Animated, Dimensions } from "react-native";
import { Divider, Utils, TYFlatList, Popup, TopBar, Toast } from "tuya-panel-kit";
import Res from '../../res';
import TYSdk from '../../api';
import dpCodes from '../../config/dpCodes';
import { arrayToObject, debounce } from "../../utils";
import Strings from '../../i18n';
import SwitchButton from '../../components/SwitchButton';
import style from '../../config/style';

const { convertX: cx } = Utils.RatioUtils;
const { convertY: cy, viewWidth, viewHeight } = Utils.RatioUtils;

const TYEvent = TYSdk.event;
const TYDevice = TYSdk.device;
const TYNative = TYSdk.native;
const TYMobile = TYSdk.mobile;

const {
  no_disturb: no_disturbCode,
  physical_controls_locked: physical_controls_lockedCode,
  alarm: alarmCode,
  switch_status: switch_statusCode,
  repeat_cycle: repeat_cycleCode,
  enable_time_period: enable_time_periodCode,
} = dpCodes;


class SettingScene extends Component {
  static propTypes = {
    // dps: PropTypes.arrayOf(
    //   PropTypes.shape({
    //     code: PropTypes.string.isRequired,
    //   })
    // ).isRequired,
  };


  constructor(props) {
    super(props);
    const { no_disturb } = this.props;
    this.state = {
      startTimeStr: null,
      endTimeStr: null,
      weekdayString: null,
      showTop:true,
    };

    this.refreshData();

  }

  componentDidMount() {

  }

  refreshData = debounce(v => {
    const { repeat_cycle, enable_time_period } = this.props;

    // 开始时间 结束时间
    console.log('勿扰时间 enable_time_period', enable_time_period);
    let startTimeStr = '';
    let endTimeStr = '';
    const parts = enable_time_period.split('-');
    if (parts.length >= 2) {
      startTimeStr = parts[0].slice(0, -3);
      endTimeStr = parts[parts.length - 1].slice(0, -3);
    }

    // 重复周期
    console.log('重复',repeat_cycle);
    let binaryString = repeat_cycle.toString(2);
    binaryString = binaryString.padStart(7, "0"); // 字符串前面补0，7是目标长度
    console.log('binaryString', binaryString);


    // 解析星期几
    let week ;
    week = TYSdk.doNotDisturbChangeToWeekdays(binaryString);
    console.log('week', week);
    this.setState({ startTimeStr, endTimeStr, weekdayString: week });
  });

  onDoNotDisturbClick= (() => {
    TYSdk.Navigator.push({
      id: 'doNotDisturb',
      isNeedRefresh: ( need ) => {
        // 刷新界面
        console.log('need refresh', need);
        if (need){
          this.refreshData();
        }
      },
    });
  });

  lockView(){
    const { physical_controls_locked } = this.props;
    return(
      <View style={[styles.cell, { height: 72}]}>
        <View style={[style.twoLines,{marginRight: 40}]}>
          <Text style={styles.boldText}>{Strings.list_item_v_chip_title}</Text>
          <Text style={[styles.subTitle, { marginTop: 5 }]}>{Strings.list_item_v_chip_desc}</Text>
        </View>
        <SwitchButton
          disabled={!fishtank_switch}
          style={{ marginRight: 10, width: 44 }}
          value={physical_controls_locked}
          onValueChange={v => {
            TYDevice.putDeviceData({
              [physical_controls_lockedCode]: v
            });
          }}
        />
      </View>
    );
  }

  // 分割线
  lineView() {
    return (
      <Divider style={{ marginTop: 10, alignSelf: 'center' }} color="#E5E5E5" width={Dimensions.get('window').width-60} />
    );
  }

  topView() {
    return (
      <TopBar.Container
        background="#FFFFFF"
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action size={20} source={Res.fback} color="#4C4C4C" onPress={() => TYSdk.Navigator.pop()} />
        <TopBar.Content />
      </TopBar.Container>
    );
  }


  render() {

    const { no_disturb, physical_controls_locked, alarm, switch_status } = this.props;
    const { startTimeStr, endTimeStr, weekdayString,showTop } = this.state;
    let data = [
      {
        key: '0',
        title: Strings.list_item_no_disturb_title,//'勿扰模式',
        // value: true,
        // styles: { content: { marginStart: 20, marginEnd: 40 } },
        Action: (
          <SwitchButton
            style={{ marginRight: 5, marginTop: 5 }}
            value={no_disturb}
            onValueChange={v => {
              TYDevice.putDeviceData({
                [no_disturbCode]: v,
              });
            }}
          />
        ),
      },
      {
        key: '1',
        title: Strings.list_item_no_disturb_setting_title,//'勿扰设置',
        subTitle: weekdayString,
        value: startTimeStr + '-' + endTimeStr,
        arrow: true,
        onPress: () => {
          TYSdk.Navigator.push({
            id: 'doNotDisturb',
            isNeedRefresh: ( need ) => {
              // 刷新界面
              console.log('need refresh', need);
              if (need) {
                this.refreshData();
              }
            },
          });
        },
      },
      {
        key: '2',
        title: Strings.list_item_v_chip_title,//'童锁',
        subTitle: Strings.list_item_v_chip_desc,//'开启后，只可用App控制鱼缸',
        Action: (
          <SwitchButton
            style={{ marginRight: 5, marginTop: 5 }}
            value={physical_controls_locked}
            onValueChange={v => {
              TYDevice.putDeviceData({
                [physical_controls_lockedCode]: v,
              });
            }}
          />
        ),
      },
      {
        key: '3',
        title: Strings.list_item_alarm_title,//'提示音',
        Action: (
          <SwitchButton
            style={{ marginRight: 5, marginTop: 5 }}
            value={alarm}
            onValueChange={v => {
              TYDevice.putDeviceData({
                [alarmCode]: v,
              });
            }}
          />
        ),
      },
      {
        key: '4',
        title: Strings.list_item_indicator_light_title,//'指示灯',
        Action: (
          <SwitchButton
            style={{ marginRight: 5, marginTop: 5 }}
            value={switch_status}
            onValueChange={v => {
              TYDevice.putDeviceData({
                [switch_statusCode]: v,
              });
            }}
          />
        ),
      },
      {
        key: '5',
        title: Strings.list_item_temp_warning_setting_title,//'温度提示设置',
        arrow: true,
        onPress: () => {
          TYSdk.Navigator.push({
            id: 'tempSetting',
          });
        },
      },
    ];

    // if (!TYSdk.devInfo.isShare){
    //   data.splice(2, 1);
    // }



    return (
      <View style={styles.container}>
         { showTop ? this.topView() : null }
        {/* 设置 */}
        <Text style={{ marginStart: 31, marginTop: 3, fontSize: 30, fontWeight:300, lineHeight: 40, color: "#000000CC" }}>{Strings.page_title_setting}</Text>

        <View style={ fishtank_switch ? style.grayHidden : style.grayBackground }>

          {/* 勿扰模式 开关 */}
          <View style={styles.cell}>
            <Text style={styles.boldText}>{Strings.list_item_no_disturb_title}</Text>
            <SwitchButton
              disabled={!fishtank_switch}
              style={{ marginRight: 10 }}
              value={no_disturb}
              onValueChange={v => {
                TYDevice.putDeviceData({
                  [no_disturbCode]: v
                });
              }}
            />
          </View>

          {/*/!* 勿扰设置 *!/*/}
          <TouchableOpacity
            disabled={!fishtank_switch}
            style={[styles.cell, { height: 72}]}
            onPress={() => {
              this.onDoNotDisturbClick();
            }}
          />
        </View>

        {/* 勿扰设置 */}
        <TouchableOpacity
          style={styles.cell}
          onPress={() => {
            this.onDoNotDisturbClick();
          }}
        >
          <View style={style.twoLines}>
            <Text style={styles.boldText}>{Strings.list_item_no_disturb_setting_title}</Text>
            <Text style={[styles.subTitle, { marginTop: 5 }]}>{weekdayString}</Text>
          </View>
          <View style={styles.iconAndText}>
            <Text style={styles.subTitle}>{startTimeStr + '-' + endTimeStr}</Text>
            <Image style={styles.arrow} source={Res.enter} />
          </View>
        </TouchableOpacity>

        {/* 童锁 分享设备不显示 */}
        { TYSdk.devInfo.isShare ? null : this.lockView() }

        {/* 提示音 */}
        <View style={styles.cell}>
          <Text style={styles.boldText}>{Strings.list_item_alarm_title}</Text>
          <SwitchButton
            style={{ marginRight: 10 }}
            value={alarm}
            onValueChange={v => {
              TYDevice.putDeviceData({
                [alarmCode]: v
              });
            }}
          />
        </View>

        {/* 提示灯 */}
        <View style={styles.cell}>
          <Text style={styles.boldText}>{Strings.list_item_indicator_light_title}</Text>
          <SwitchButton
            style={{ marginRight: 10 }}
            value={switch_status}
            onValueChange={v => {
              TYDevice.putDeviceData({
                [switch_statusCode]: v
              });
            }}
          />
        </View>

        {/* 温度提醒设置 */}
        <TouchableOpacity
          style={styles.cell}
          onPress={() => {
            TYSdk.Navigator.push({
              id: 'tempSetting',
            });
          }}
        >
          <Text style={styles.boldText}>{Strings.list_item_temp_warning_setting_title}</Text>
          <Image style={styles.arrow} source={Res.enter} />
        </TouchableOpacity>



        <View style={styles.spliceline}>
          { this.lineView() }
        </View>
        {/* 使用手册 */}
        <View style={{ backgroundColor: '#FFFFFF', height: 30, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
          <Text style={{ marginStart: 30, fontSize: 12, fontWeight: 'bold', color: '#636363' }}>{Strings.list_group_title_0}</Text>
        </View>

        {/* 使用帮助 */}
        <TouchableOpacity
          style={[styles.cell]}
          onPress={() => {
            TYSdk.Navigator.push({
              id: 'helpList',
            });
          }}
        >
          <Text style={styles.boldText}>{Strings.list_item_use_help}</Text>
          <Image style={styles.arrow} source={Res.enter} />
        </TouchableOpacity>

        {/* 新手引导视频 */}
        <TouchableOpacity
          style={[styles.cell]}
          onPress={() => {
            TYSdk.Navigator.push({
              id: 'videoList',
            });
          }}
        >
          <Text style={styles.boldText}>{Strings.list_item_new_player_video_guide_title}</Text>
          <Image style={styles.arrow} source={Res.enter} />
        </TouchableOpacity>

        {/*<TYFlatList*/}
        {/*  style={{*/}
        {/*    alignSelf: 'stretch',*/}
        {/*    backgroundColor: '#f5f5f5',*/}
        {/*    height: 850,*/}
        {/*  }}*/}
        {/*  separatorStyle={{ backgroundColor: '#FFFFFF' }}*/}
        {/*  scrollEnabled={false}*/}
        {/*  data={help}*/}
        {/*/>*/}

      </View>
    );


  }

}


const help = [
  {
    key: '0',
    title: Strings.list_group_title_0,//'使用手册',
    arrow: true,
    onPress: () => {
      TYSdk.Navigator.push({
        id: 'helpList',
      });
    },
    // styles: { content: { marginStart: 20, marginEnd: 40 } },
  },
  {
    key: '1',
    title: Strings.list_item_new_player_video_guide_title,//'新手指导视频',
    arrow: true,
    onPress: () => {
      TYSdk.Navigator.push({
        id: 'videoList',
      });
    },
  },
];


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  spliceline: {
    backgroundColor: 'white',
    height: cx(28),
    justifyContent: 'center',
  },
  cell: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    // backgroundColor: '#b4dcec',
    height: 60,
    marginStart: 30,
    marginEnd: 20,
  },
  boldText: {
    marginLeft: 0,
    fontSize: 16,
    fontWeight: 'bold',
    color: '#000',
  },
  subTitle: {
    fontSize: 14,
    fontWeight: '400',
    color: '#757575FF',
  },
  iconAndText: {
    flexDirection: 'row',
    alignItems: 'center',
  },

});

export default connect(({ dpState }) => ({
  no_disturb: dpState[no_disturbCode],
  physical_controls_locked: dpState[physical_controls_lockedCode],
  alarm: dpState[alarmCode],
  switch_status: dpState[switch_statusCode],
  repeat_cycle: dpState[repeat_cycleCode],
  enable_time_period: dpState[enable_time_periodCode],

}))(SettingScene);
